/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.handler.hj212.parse;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.xy.format.hbt212.core.T212Mapper;
import com.xy.format.hbt212.core.feature.VerifyFeature;
import com.xy.format.hbt212.exception.T212FormatException;
import com.xy.format.hbt212.model.standard.Data;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author
 * @apiNote 环境国标数据信息解析
 * @date 2023/3/3 14:51
 */
public class EnvHJ212Parse {

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(EnvHJ212Parse.class);

    /**
     * 环境国标（HJ-212）数据解析成符合物模型定义数据集
     */
    public static JSON envDataParse(String msg, JSONArray configList){
        //T212Mapper 配置默认解析器和默认校验器
        try {

            Data data = parseHJ212Data(msg);
            JSONObject parseData = new JSONObject();
            //上传污染物小时数据
            String deviceId = data.getMn();
            String createTime = LocalDateTime.parse(data.getCp().getDataTime(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+08:00'"));
            //数据时间周期
            String interval = data.getCn();
            String st = data.getSt();

            parseData.putByPath("deviceId",deviceId);
            parseData.putByPath("createTime",createTime);

            String tableName = null;
            switch (interval){
                case "2011":{
                    //实时数据
                    tableName = "I"+ st + "_rtd";
                }break;
                case "2051":{
                    //分钟数据
                    tableName = "I"+ st + "_minute";
                }break;
                case "2061":{
                    //小时数据
                    tableName = "I"+ st + "_hour";
                }break;
                case "2031":{
                    //日数据
                    tableName = "I"+ st + "_day";
                }break;
            }
            parseData.putByPath("interval",tableName);
            //取出配置信息用于
            for (Object obj : configList) {
                JSONObject config = JSONUtil.parseObj(obj);

                String code = config.getStr("code");
                String key = config.getStr("key");
                //模型字段名
                String field_name = config.getStr("model_attribute_name");
//                String st = config.getStr("st");
//                String cn = config.getStr("cn");
                if(StringUtils.equalsIgnoreCase(config.getStr("st") , st)
                        && StringUtils.equalsIgnoreCase(config.getStr("cn") , interval)
                ){

                    if(data.getCp().getPollution().containsKey(code)){
                        //存在对应的code信息
                        JSONObject pollution = JSONUtil.parseObj(data.getCp().getPollution().get(code));
                        for (String pkey : pollution.keySet()) {
                        	if(StringUtils.equalsIgnoreCase(pkey , key)) {
                        		parseData.putByPath(field_name,pollution.get(pkey));
                        	}
                        }
                    }
                }else {
                    continue;
                }
            }
            logger.info("hj212数据为-- " + JSONUtil.toJsonStr(parseData));
            parseData.putByPath("_origin_data",msg);
            return parseData;
        }catch (Exception e){
            logger.error("hj-212 解析成Data对象数据出错--------------------");
            logger.error("{}", e);
        }

        return null;
    }

    /**
     * 符合HJ212标准的数据包解析
     */
    public static Data parseHJ212Data(String msg) {
        Data data = null;
        try {
            T212Mapper mapper = new T212Mapper()
                    .enableDefaultVerifyFeatures()
    //                    .enableDefaultVerifyFeatures();
                    .enable(VerifyFeature.DATA_CRC);//启用CRC校验

            data = mapper.readData(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (T212FormatException e) {
            e.printStackTrace();
        }
        return data;
    }
}
